package com.android.settings.audio.peq.peq.widget;

import static com.android.settings.audio.plugin.View.FileSelectView.CHANGE_SAVE_PATH;
import static com.android.settings.audio.plugin.View.FileSelectView.GetPathAction;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.settings.R;
import com.android.settings.audio.peq.peq.ui.MixerCallback;
import com.android.settings.audio.peq.peq.ui.dialog.CommanDialog;
import com.android.settings.audio.peq.skin.SkinManager;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.FileUtil;
import com.android.settings.audio.peq.util.GetSize;
import com.android.settings.audio.peq.util.LogPlus;
import com.android.settings.audio.peq.util.NameString;
import com.android.settings.audio.peq.util.ShareprefenceTool;
import com.android.settings.audio.peq.util.ToastTool;
import com.android.settings.audio.plugin.View.FileSelectView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * Created by WinsonLi on 2017/8/29.
 */

public class PEQImportDialog {
    private CommanDialog mDialog;
    private Context mContext;
    private PathSeletedBroadcastReceiver mPathSeletedBroadcastReceiver;
    private static final String TAG = "PEQImportDialog";

    public PEQImportDialog(Context context) {
        this.mContext = context;
    }

    /**
     * 自定义弹框 dialog
     */
    public void initSavaCustomMixerDialog() {
        mDialog = new CommanDialog(mContext, R.style.peqMyDialogStyle, CommanDialog.STYLE_NOTITLE_NOBUTTON);
        mDialog.addView(R.layout.peq_dialog_eq_import_newcreate_newuistyle);
        View view = mDialog.getContentView();
        mDialog.show();
        TextView tv_commit = view.findViewById(R.id.commit);
        TextView tv_cancle = view.findViewById(R.id.cancl);
        EditText editText = view.findViewById(R.id.editText);
        boolean hideSaveToLocalFile = true;
        if (hideSaveToLocalFile) view.findViewById(R.id.re_range_low).setVisibility(View.GONE);
        CheckBox checkbox_save = view.findViewById(R.id.checkbox_save);
        SkinManager.get().setCheckBoxLeftDrawable(checkbox_save, R.drawable.peq_skin_selector_checkbox_circle_3);
        editText.requestFocus();
        tv_commit.setOnClickListener(v -> {
            String value = editText.getText().toString();
            if (value.length() > 0) {
                if (checkbox_save.isChecked()) {
                    mCurrentSavetoLocalName = value;
                    initBroadcastReceiver(mContext);
                    showSavePathEnsureDialog(mContext, value);
                    saveToDatabase(value);
                    mDialog.dismiss();
                } else {
                    saveToDatabase(value);
                }
            } else {
                ToastTool.showToast(mContext.getApplicationContext(), mContext.getResources().getString(R.string.peq_eq_setting_name_not_empty));
            }
        });
        tv_cancle.setOnClickListener(v -> {
            mDialog.dismiss();
            initDialog();
        });
    }

    private String mCurrentSavetoLocalName = null;

    private void showSavePathEnsureDialog(final Context context, String name) {
        final CommanDialog dialog = new CommanDialog(context,
                R.style.peqMyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
        dialog.setCanceledOnTouchOutside(true);
        dialog.addView(R.layout.peq_dialog_content_delete_audio);
        dialog.titleTextView.setText(NameString.getResoucesString(context, R.string.peq_save_path));
        mixerCallback = MixerCallback.getInstance();
        View contentView = dialog.getContentView();
        TextView tv_content = (TextView) contentView.findViewById(R.id.tv_dialog_content);
        tv_content.setText(getFileSavePath(mContext));
        dialog.ok.setText(R.string.peq_ensure);
        dialog.cancle.setText(R.string.peq_motify);
        dialog.ok.setOnClickListener(v -> {
            saveDataToLocal(name);
            dialog.dismiss();
        });
        dialog.cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileExplorer();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    public void initDialog() {
        if (mDialog == null) {
            mDialog = new CommanDialog(mContext, R.style.peqMyDialogStyle, CommanDialog.STYLE_NOTITLE_NOBUTTON);
            mDialog.addView(R.layout.peq_dialog_eq_import);
            mDialog.setCanceledOnTouchOutside(true);
            mixerCallback = MixerCallback.getInstance();
            View contentView = mDialog.getContentView();
            mDialog.show();
            TextView textView = contentView.findViewById(R.id.text_new_create);
            TextView save_to_local = contentView.findViewById(R.id.save_to_file);
            save_to_local.setOnClickListener(v -> {
                mDialog.dismiss();
                initBroadcastReceiver(mContext);
                showSavePathInfoDialog(mContext);
            });
            textView.setOnClickListener(v -> {
                mDialog.dismiss();
                initNewCreate(false);
            });
        }
    }

    private void showSavePathInfoDialog(final Context context) {
        final CommanDialog dialog = new CommanDialog(context,
                R.style.peqMyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
        dialog.setCanceledOnTouchOutside(true);
        dialog.addView(R.layout.peq_dialog_content_delete_audio);
        dialog.titleTextView.setText(NameString.getResoucesString(context, R.string.peq_save_path));

        View contentView = dialog.getContentView();
        TextView tv_content = (TextView) contentView.findViewById(R.id.tv_dialog_content);
        tv_content.setText(getFileSavePath(mContext));
        dialog.ok.setText(R.string.peq_ensure);
        dialog.cancle.setText(R.string.peq_motify);
        dialog.ok.setOnClickListener(v -> {
            initNewCreate(true);
            dialog.dismiss();
        });
        dialog.cancle.setOnClickListener(v -> {
            showFileExplorer();
            dialog.dismiss();
        });
        dialog.show();
    }

    private void showFileExplorer() {
        /*boolean lacksPermissions = PermssionUtils.lacksPermissions(mContext, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                ToastTool.showToast(mContext.getApplicationContext(), mContext.getResources().getString(R.string.pession_error));
                return;
            }
        } else if (lacksPermissions) {
            ToastTool.showToast(mContext.getApplicationContext(), mContext.getResources().getString(R.string.pession_error));
            return;
        }*/
        if (BuildConfig.DEBUG) LogPlus.d("startPathSelectActivity");
        starPathSelectActivity();//on path selected via broadcastreceiver
    }

    private void starPathSelectActivity() {
        /*Intent intent = new Intent(mContext, DspFileSelectActivity.class);
        Bundle bundle = new Bundle();
        String savePath = getFileSavePath(mContext);
        bundle.putLong(DspFileSelectActivity.SIZE_LIMIT, 1024 * 20);
        bundle.putString(DspFileSelectActivity.START_PATH, savePath);
        bundle.putBoolean(DspFileSelectActivity.IS_SELECT_SAVE_PATH, true);
        intent.putExtra(DspFileSelectActivity.SELECT_FILE, bundle);
        mContext.startActivity(intent);*/
    }

    public static String getFileSavePath(Context context) {
        String savePath = context.getExternalFilesDir(null).toString() + File.separator + "PeqFile" + File.separator;
        return ShareprefenceTool.getInstance().getStringShareprefence("peq_file_save_path", context, savePath);
    }

    /**
     * 创建新建设定名 dialog
     */
    public void initNewCreate(boolean save2Local) {
        mDialog = new CommanDialog(mContext, R.style.peqMyDialogStyle, CommanDialog.STYLE_NOTITLE_NOBUTTON);
        mDialog.addView(R.layout.peq_dialog_eq_import_newcreate);
        View view = mDialog.getContentView();
        mDialog.show();
        TextView tv_commit = view.findViewById(R.id.commit);
        TextView tv_cancle = view.findViewById(R.id.cancl);
        EditText editText = view.findViewById(R.id.editText);
        tv_commit.setOnClickListener(v -> {
            String value = editText.getText().toString();
            if (value.length() > 0) {
                if (save2Local) {
                    saveDataToLocal(value);
                    mDialog.dismiss();
                } else {
                    saveToDatabase(value);
                }
            } else {
                ToastTool.showToast(mContext.getApplicationContext(), mContext.getResources().getString(R.string.peq_eq_setting_name_not_empty));
            }
        });
        tv_cancle.setOnClickListener(v -> {
            mDialog.dismiss();
            initDialog();
        });
    }

    private void saveDataToLocal(String title) {
        String savePath = getFileSavePath(mContext);

        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String filePath = savePath + title + ".peq";
        boolean success = mixerCallback.getMixer().newMixerLocalSetting(title, filePath);
        if (!success) {
            ToastTool.showToast(mContext.getApplicationContext(), mContext.getResources().getString(R.string.peq_store_failure));
            return;
        }

//        String dilogText = mContext.getResources().getString(R.string.store_successful);
//        Observable.just(0).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<Integer>() {
//                    @Override
//                    public void accept(Integer integer) throws Exception {
//                        showPathMessage(mContext, dilogText, filePath);
//                    }
//                });
    }

    private void saveToDatabase(String title) {
        if (mixerCallback == null) {
            mixerCallback = MixerCallback.getInstance();
        }
        MixerCallback.MixerMonitor mixer = mixerCallback.getMixer();
        if (mixer == null) return;
        if (mixer.newSettings(true, title)) {
            mDialog.dismiss();
        }
    }

    public static void showPathMessage(Context context, String title, String path) {
        final CommanDialog pathMessageDialog = new CommanDialog(context, R.style.peqMyDialogStyle, CommanDialog.STYLE_4_HASTITLE_ONEBUTTON);
        pathMessageDialog.setCanceledOnTouchOutside(true);
        pathMessageDialog.titleTextView.setText(title);

        TextView pathText = new TextView(context);
        pathText.setText(path);
        int padding = GetSize.dip2px(context, 10);
        pathText.setPadding(padding, padding, padding, padding);
        pathText.setSingleLine(false);
        pathText.setTextSize(15);
        pathText.setTextColor(Color.GRAY);
        pathMessageDialog.addView(pathText);

        pathMessageDialog.ok.setText(NameString.getResoucesString(context, R.string.peq_back));
        pathMessageDialog.ok.setOnClickListener(v -> pathMessageDialog.dismiss());
        pathMessageDialog.show();
    }

    /***
     * 创建导入设定 dialog
     * @return
     */
    public void togetLocalFile(Context context) {
        initBroadcastReceiver(context);
        startFileSelectActivity();
    }

    private void unregisterBroadcast() {
        if (mPathSeletedBroadcastReceiver != null) {
            mContext.unregisterReceiver(mPathSeletedBroadcastReceiver);
            //LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mPathSeletedBroadcastReceiver);
            mPathSeletedBroadcastReceiver = null;
        }
    }

    private void startFileSelectActivity() {
        Intent intent = new Intent(mContext, com.android.settings.audio.plugin.DspFileSelectActivity.class);
        Bundle bundle = new Bundle();
        ArrayList<String> strings = new ArrayList<>();
        strings.add("peq");
        strings.add("txt");//2023.6.9 PEQ 的导入，增加一个 AutoEQ 的格式。(.txt)
        String savePath = getFileSavePath(mContext);
        bundle.putStringArrayList(com.android.settings.audio.plugin.DspFileSelectActivity.FILE_TYPE, strings);
        bundle.putLong(com.android.settings.audio.plugin.DspFileSelectActivity.SIZE_LIMIT, 1024 * 20);
        bundle.putString(com.android.settings.audio.plugin.DspFileSelectActivity.START_PATH, savePath);
        intent.putExtra(com.android.settings.audio.plugin.DspFileSelectActivity.SELECT_FILE, bundle);
        mContext.startActivity(intent);
    }

    private void initBroadcastReceiver(Context context) {
        if (mPathSeletedBroadcastReceiver != null) {
            unregisterBroadcast();
        }
        mPathSeletedBroadcastReceiver = new PathSeletedBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CHANGE_SAVE_PATH);
        intentFilter.addAction(GetPathAction);
        context.registerReceiver(mPathSeletedBroadcastReceiver, intentFilter);
        //LocalBroadcastManager.getInstance(context).registerReceiver(mPathSeletedBroadcastReceiver, intentFilter);
    }

    private class PathSeletedBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogPlus.d("###action:" + action);
            try {
                Bundle extras = intent.getBundleExtra("dspdata_path");
                String targetPath = extras.getString("targetPath");
                Log.d(TAG, "onReceive: targetPath" + targetPath);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            if (GetPathAction.equals(action)) {
                saveMsebDataToLocal(intent, context);
                unregisterBroadcast();
            } else if (CHANGE_SAVE_PATH.equals(action)) {
                Bundle extras = intent.getBundleExtra("dspdata_path");
                String targetPath = extras.getString("targetPath");
                Log.e(TAG, "onReceive: " + targetPath);
                ShareprefenceTool.getInstance().setStringSharedPreference("peq_file_save_path", targetPath, mContext);
                if (mCurrentSavetoLocalName != null) {
                    saveDataToLocal(mCurrentSavetoLocalName);
                } /*else {
                    initNewCreate(Mixer,true);
                }*/
                unregisterBroadcast();
            }
        }
    }

    public void saveMsebDataToLocal(Intent intent, Context context) {
        Bundle extras = intent.getBundleExtra("dspdata_path");
        String targetPath = extras.getString("targetPath");
        Log.d(TAG, "onReceive: targetPath" + targetPath);
        File file = new File(targetPath);
        if (file.exists()) {
            try {
                String string = FileUtil.readFileTOString(file);
                Log.d(TAG, "onReceive: string: " + string);
                MixerCallback.getInstance().getMixer().importDataToLocal(string, file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                ToastTool.showToast(context.getApplicationContext(), context.getResources().getString(R.string.peq_import_failed));
            }
        } else {
            ToastTool.showToast(context.getApplicationContext(), context.getResources().getString(R.string.peq_import_failed));
        }
    }

    public CommanDialog getDialog() {
        return mDialog;
    }

    private void onCancel() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.cancel();
        }
    }

    public void showDialog() {
        if (mDialog != null) {
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }
    }

    private MixerCallback mixerCallback;
}
